//
//  LoginServer.m
//  pa
//
//  Created by HaiJiao Chen on 12-7-22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginServer.h"
#import "FilePack.h"
#import "XMLObject.h"
#import "ASIHTTPRequest.h"
#import "CHJAlertView.h"
#import "FilePack.h"
#import "AppDelegate.h"
#include "text_def.h"

LoginServer* LoginServer_shared_instance = nil;

@implementation LoginServer
@synthesize data;

- (NSString*)savePath
{
    return [[AppDelegate sharedInstance].cachePath stringByAppendingString:@"/server.plist"];    
}
//http://paperlessapi.c1.concretego.com/paperlessapi.asmx/getServerList?Language=en-US
- (id)init
{
    self = [super init];
    if (self)
    {
        normalQuene = [[ASINetworkQueue alloc] init];
        [normalQuene setDelegate:self];
        [normalQuene setRequestDidFinishSelector:@selector(requestFinished:)];
        [normalQuene setRequestDidFailSelector:@selector(requestFailed:)];
        normalQuene.shouldCancelAllRequestsOnFailure = NO;
        [normalQuene go];
        
//        NSString* api = [NSString stringWithFormat:@"%@/getServerList?&Language=%@", SERVER_URL,[FilePack currentlanguage]];
//        NSURL *url = [NSURL URLWithString:api];
//        ASIHTTPRequest* request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
//        [normalQuene addOperation:request];

    }
    return self;
}

- (void)dealloc
{
    [data release];
    [normalQuene cancelAllOperations];
    [normalQuene setDelegate:nil];
    [normalQuene release];
    [waittingAlertView close];
    [super dealloc];
}

- (void)construct
{
    data = [[NSMutableArray alloc] initWithCapacity:10];
    [data addObjectsFromArray:[NSArray arrayWithContentsOfFile:[self savePath]]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(languageChanged) name:MultiLanguageChangeNotification object:nil];

    BOOL find = NO;
    for (NSMutableDictionary* dic in data)
    {
        if ([[dic valueForKey:@"url"] isEqual:SERVER_URL])
        {
            find = YES;
            break;
        }
    }
    if (find == NO)
    {
        [data addObject:
         [NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"name", SERVER_URL, @"url", nil]];
    }
    
    
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 155, 37);
    button.center = CGPointMake(512, 300);
    [button setBackgroundImage:[UIImage imageNamed:@"btn_sing_in"] forState:UIControlStateNormal];
    button.hidden = YES;
    button.tag = 100;
    [button addTarget:self action:@selector(retry:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:[FilePack getStringByID:STR_RETRY] forState:UIControlStateNormal];
    [button.titleLabel setFont:[UIFont systemFontOfSize:27]];
    
    waittingAlertView = [[CHJAlertView alloc] init];
    [waittingAlertView setLoadingText:[FilePack getStringByID:STR_PLEASE_WAIT] animated:YES];
    [waittingAlertView addSubview:button];
    [waittingAlertView show];
    [waittingAlertView release];
    [[AppDelegate sharedInstance] sendHttpRequest:@"getServerList?" params:nil delegate:self];

}
- (void)languageChanged
{
    [[AppDelegate sharedInstance] sendHttpRequest:[NSString stringWithFormat:@"getServerList?&Language=%@",[FilePack currentlanguage]] params:nil delegate:self];
}

//- (void)requestFinished:(ASIHTTPRequest *)request
//{
//    XMLObject* xml = [XMLObject parse:[request rawResponseData]];
//    if ([xml getIntForKey:@"ret" defaultValue:0] == 1)
//    {
//        int count = [data count];
//        for (int i = 0; i < count; i++)
//        {
//            NSMutableDictionary* dic = [data objectAtIndex:i];
//            if ([dic valueForKey:@"changable"] == nil)
//            {
//                [data removeObjectAtIndex:i];
//                i--;
//                count--;
//            }
//        }
//        XMLObject* result = [xml getXMLObjectForKey:@"Servers"];
//        count = [result getCount];
//        for (int i = count-1; i >= 0; i--)
//        {
//            XMLObject* s = [result getXMLObjectForIndex:i];
//            NSString* name = [s getStringForKey:@"Name" defaultValue:nil];
//            NSString* url = [s getStringForKey:@"Url" defaultValue:nil];
//            if (name != nil && url != nil)
//            {
//                [data insertObject:
//                 [NSMutableDictionary dictionaryWithObjectsAndKeys:name,@"name",url,@"url", nil] 
//                              atIndex:0];
//            }
//        }
//        
//        
//        BOOL find = NO;
//        for (NSMutableDictionary* dic in data)
//        {
//            if ([[dic valueForKey:@"url"] isEqual:SERVER_URL])
//            {
//                find = YES;
//                break;
//            }
//        }
//        if (find == NO)
//        {
//            [data addObject:
//             [NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"name", SERVER_URL, @"url", nil]];
//        }
//
//        
//        [data writeToFile:[self savePath] atomically:YES];
//        [[NSNotificationCenter defaultCenter] postNotificationName:DataSourceChangeNotification object:self];
//        [waittingAlertView close];
//        waittingAlertView = nil;
//    }
//    else
//    {
//        [waittingAlertView setTitle:[xml getStringForKey:@"error" defaultValue:[FilePack getStringByID:STR_ERROR_OCCUR]] max_width:160 animated:YES];
//        [waittingAlertView closeInTime:2];
//        waittingAlertView = nil;
//    }
//}
//
//- (void)requestFailed:(ASIHTTPRequest *)request
//{
//    [waittingAlertView setTitle:[FilePack getStringByID:STR_ERROR_OCCUR] max_width:160 animated:YES];
//    [waittingAlertView closeInTime:2];
//    waittingAlertView = nil;
//}

- (void)addServerWithName:(NSString*)name andUrl:(NSString*)url
{
    [data insertObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:name,@"name",url,@"url",[NSNumber numberWithBool:YES],@"changable", nil] atIndex:0];
    [data writeToFile:[self savePath] atomically:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:DataSourceChangeNotification object:self];
}
- (void)removeServerWithIndex:(int)index
{
    if (index >= 0 && index < [data count])
    {
        [data removeObjectAtIndex:index];
        [data writeToFile:[self savePath] atomically:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:DataSourceChangeNotification object:self];
    }
}

+ (LoginServer*)sharedInstance
{
    if (LoginServer_shared_instance == nil)
    {
        LoginServer_shared_instance = [[LoginServer alloc] init];
        [LoginServer_shared_instance construct];
    }
    return LoginServer_shared_instance;
}

-(void)showRetry:(NSString*)error
{
    [waittingAlertView setTitle:error max_width:160 animated:YES];
    //[waittingAlertView closeInTime:2];
    //waittingAlertView = nil;
    UIButton* button = (UIButton*)[waittingAlertView viewWithTag:100];
    button.hidden = NO;
}
-(void)requestFinished:(NSMutableDictionary*)params data:(XMLObject*)xml succ:(BOOL)succ
{
    if (succ)
    {
        if ([xml getIntForKey:@"ret" defaultValue:0] == 1)
        {
            int count = [data count];
            for (int i = 0; i < count; i++)
            {
                NSMutableDictionary* dic = [data objectAtIndex:i];
                if ([dic valueForKey:@"changable"] == nil)
                {
                    [data removeObjectAtIndex:i];
                    i--;
                    count--;
                }
            }
            XMLObject* result = [xml getXMLObjectForKey:@"Servers"];
            count = [result getCount];
            for (int i = count-1; i >= 0; i--)
            {
                XMLObject* s = [result getXMLObjectForIndex:i];
                NSString* name = [s getStringForKey:@"Name" defaultValue:nil];
                NSString* url = [s getStringForKey:@"Url" defaultValue:nil];
                if (name != nil && url != nil)
                {
                    [data addObject:
                     [NSMutableDictionary dictionaryWithObjectsAndKeys:name,@"name",url,@"url", nil]];
                }
            }
            
            
            BOOL find = NO;
            for (NSMutableDictionary* dic in data)
            {
                if ([[dic valueForKey:@"url"] isEqual:SERVER_URL])
                {
                    find = YES;
                    break;
                }
            }
            if (find == NO)
            {
                [data addObject:
                 [NSMutableDictionary dictionaryWithObjectsAndKeys:@"", @"name", SERVER_URL, @"url", nil]];
            }

            
            [data writeToFile:[self savePath] atomically:YES];
            [[NSNotificationCenter defaultCenter] postNotificationName:DataSourceChangeNotification object:self];
            [waittingAlertView close];
            waittingAlertView = nil;
        }
        else
        {
            [self showRetry:[xml getStringForKey:@"error" defaultValue:[FilePack getStringByID:STR_ERROR_OCCUR]]];
        }
    }
    else
    {
        [self showRetry:[FilePack getStringByID:STR_ERROR_OCCUR]];
    }
}



- (void)retry:(UIButton*)sender
{
    sender.hidden = YES;
    [waittingAlertView setLoadingText:[FilePack getStringByID:STR_PLEASE_WAIT] animated:YES];
    [[AppDelegate sharedInstance] sendHttpRequest:@"getServerList?" params:nil delegate:self];

}
@end
